package queue;


//双向链表模拟实现队列
public class MyLinkedListQueue {

    //节点，内部类
    public static class ListNode {
        public int val;
        public ListNode prev;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode head;
    public ListNode last;

    public int usedSize;


    //入队列,尾插
    public boolean offer(int val) {
        ListNode node = new ListNode(val);
        if (head == null) {
            head = node;
            last = node;
        } else {
            last.prev.next = node;
            node.prev = last;
            last = node;
        }
        usedSize++;
        return true;
    }

    //出队列，头删
    public int poll() throws QueueEmptyException {
        if (head == null)  {
            throw new QueueEmptyException("队列为空！");
        }
        int retVal =  head.val;
        if (head.next == null) {
            head = null;
            last = null;
        } else {
            head = head.next;
            head.prev = null;
        }
        usedSize--;
        return retVal;
    }


    //获取队头元素，不删除
    public int peek() throws QueueEmptyException {
        if (head == null) {
            throw new QueueEmptyException("队列为空！");
        }
        return head.val;
    }

    public int size() {
        return usedSize;
    }

    public boolean empty() {
        return head == null;
    }


}
